import { useState , useEffect } from "react"
import { useRequest } from "ahooks"
import { UseDispatch, useDispatch } from "react-redux"
import { loginReducer } from "../store/userReducer"
import { getUserInfor } from "../services/user"
import useGetUserInfo from "./useGetUserinfo"

/**
 * 
 * @returns 
 * 统一获取用户信息，并存储在redux中
 * 返回一个状态标识即可
 */

 function useGetUserData (){
    // 登陆标识，未登陆是true
    const [waitingUserData ,setWaitingUserData] = useState(true)   
    const {userName : findUsername} = useGetUserInfo()
    const dispatch = useDispatch()

    const {run} = useRequest(getUserInfor , {
        manual : true,
        onSuccess(result){
            // 请求成功后，将用户信息存到redux中
            const {username : userName , nickname :nickName } = result
            dispatch(loginReducer({userName , nickName}))
        },
        onFinally(){
            setWaitingUserData(false)
        }
    })

    // 判断是否需要redux中是否已有用户信息，决定是否发送ajax请求
    useEffect(() => {
        // 已有用户信息，则无需重新加载
        if(findUsername){
            console.log(findUsername , ' useEffect  --  40 ')
            setWaitingUserData(false)
            return
        }

        // 手动调用请求用户信息
        run()

    },[findUsername])

    return {waitingUserData}
}

export default useGetUserData